<?php	namespace Admin\Controller;
/**
 * 学生管理控制器
 * @author 武斌   <wubin.mail@foxmail.com>
 * @Date 
 */
class StuController extends CommonController
{
	//学生管理首页
	public function index()
	{
		
		//获取全部数据
		$cid = $_GET['cid'];
		//非法参数判断，check是我们自定义方法
		$back = $this->check($cid);
		//如果返回结果是非法参数，那就刷新当前页面
		if($back['valid'] == 0)
		{//走到这里说明是非法参数
			$localCid = $back['cid'];
			header("location:index.php?m=Admin&c=Stu&a=index&cid={$localCid}");
		}
		$data = M()->query("select * from stu where cid={$cid}");
		//分配到页面
		$this->assign('data',$data);
		//分配公共头部title数据
		$this->assign("title","学生管理首页");
		$this->display();
	}
	//添加学生
	public function add()
	{
		$cid = (int)$_GET['cid'];
		//调用非法参数验证的方法,返回结果
		$back = $this->check($cid);
		if($back['valid'] == 0)
		{//走到这里说明是非法参数
			$localCid = $back['cid'];
			header("location:index.php?m=Admin&c=Stu&a=add&cid={$localCid}");
		}
		if(IS_POST)
		{
			$sname = $_POST['sname'];
			$sex = $_POST['sex'];
			$age = $_POST['age'];
			//执行添加学生表
			M()->exec("insert into stu (sname,sex,age,cid) values ('{$sname}','{$sex}',{$age},{$cid})");
			//成功提示
			$this->success("操作成功",'index.php?m=Admin&c=Stu');exit;
		}
		//加载页面
		$this->display();
	}
	//编辑学生
	public function edit()
	{
		$sid = (int)$_GET['sid'];
		$cid = (int)$_GET['cid'];
		if(IS_POST)
		{
			$sname = $_POST['sname'];
			$age = $_POST['age'];
			$sex = $_POST['sex'];
			M()->exec("update stu set sname='{$sname}',age={$age},sex='{$sex}' where sid={$sid}");
			//成功提示
			$this->success("操作成功","index.php?m=Admin&c=Stu&a=index&cid={$cid}");exit;
		}
		//获取旧数据
		$oldData = M()->query("select * from stu where sid={$sid}");
		$this->assign("oldData",$oldData[0]);
		//加载模板
		$this->display();
	}
	//非法参数验证方法
	public function check($cid)
	{
		//非法参数判断
		//$cids = [1,3,4,5,5];
		$cids = M()->query("select cid from class");
		//重组数组定义的临时空数组，最终重组完成之后的数据压入$temp
		$temp = [];
		foreach ($cids as $key => $value) {
			$temp[] = $value['cid'];
		}
		//如果get参数不在temp数组中
		if(!in_array($cid,$temp))
		{
			//错误提示
			//$this->error("非法操作","index.php?m=Admin");exit;
			//刷新当前页面
			//如果是非法参数，返回标识0
			$localCid = $temp[0];
			return ['valid'=>0,'cid'=>$localCid];
		}
		//不是非法参数，返回的标识是1
		return ['valid'=>1,'cid'=>''];
	}
}
